﻿using LitJson;
using RestAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TopVisionLog;
using AxZWANPHONELib;
using TopVisionVideoStream.TopVisionCenter;

namespace TopVisionVideoStream.Mananger
{
    public class LoginManager : IDisposable
    {
        public event LoginEventHandler LoginEvent;

        /// <summary>
        /// 登录超时计时
        /// </summary>
        private int counter = 0;
        /// <summary>
        /// 登录超时
        /// </summary>
        private int timeout = 7;

        private string tempUsername;

        private string tempPassword;

        public bool FromTVCenter = false;

        public LoginManager()
        {
            OcxApi.LogonResultEvent += OcxApi_LogonResultEvent;
            OcxApi.RegisterSoftPhoneToSSEvent += OcxApi_RegisterSoftPhoneToSSEvent;
        }

        /// <summary>
        /// 登录验证事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OcxApi_LogonResultEvent(object sender, _DZwanPhoneEvents_LogonResultEvent e)
        {
            int ret = e.lReason;
            if (ret == 403 || ret == -1)
            {
                tempUsername = tempPassword = "";
                LoginEvent?.Invoke(ret, "");
            }
        }

        /// <summary>
        /// 登录服务器状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OcxApi_RegisterSoftPhoneToSSEvent(object sender, _DZwanPhoneEvents_RegisterSoftPhoneToSSEvent e)
        {
            try
            {
                int ret = e.lType;
                LoginEvent?.Invoke(0, "");
                if (ret == 1 || ret == 8)
                {
                    Configuration.Account = tempUsername;
                    Configuration.Password = tempPassword;

                    if (FromTVCenter)
                    {
                        TVCQuerycompanyinfoModel model = new TVCQuerycompanyinfoModel();

                        model.number = Configuration.Account;

                        model.password = Configuration.Password;

                        var result = await TVCQuerycompanyinfo(model);

                        if (result == null || result.data == null || !result.success) throw new Exception("LoginManager_TVCQuerycompanyinfo result is null");

                        Configuration.CompanyID = result.data.companyid;

                        Configuration.CompanyKey = result.data.password;

                        RestAPICommon.KEY = Configuration.CompanyKey;

                        JsonData jd = new JsonData();

                        jd["account"] = tempUsername;

                        jd["password"] = tempPassword;

                        LoginEvent?.Invoke(2, jd.ToJson());
                    }
                    else
                    {
                        MQuerycompanyinfo mcominfo = new MQuerycompanyinfo(tempUsername, tempPassword);

                        mcominfo.Call((result) =>
                        {
                            try
                            {
                                Querycompanyinfo cominfo = JsonMapper.ToObject<Querycompanyinfo>(result);

                                if (cominfo == null || string.IsNullOrEmpty(cominfo.companyid) || string.IsNullOrEmpty(cominfo.password))
                                {
                                    LoginEvent?.Invoke(4, "");
                                }
                                else
                                {
                                    Configuration.CompanyID = cominfo.companyid;
                                    Configuration.CompanyKey = cominfo.password;
                                    RestAPICommon.KEY = cominfo.password;
                                    JsonData jd = new JsonData();
                                    jd["account"] = tempUsername;
                                    jd["password"] = tempPassword;
                                    LoginEvent?.Invoke(2, jd.ToJson());

                                }
                            }
                            catch (Exception ex)
                            {
                                Log(ex.Message);
                                LoginEvent?.Invoke(-1, "");
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                LoginEvent?.Invoke(4, "ERR " + ex.Message);
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">用户密码</param>
        /// <returns></returns>
        public bool Login(string userName, string password)
        {
            tempUsername = userName;
            tempPassword = password;
            var ret = OcxApi.bLogonServer2(userName, password, password);
            if (!ret)
            {
                tempUsername = tempPassword = "";
            }

            return ret;
        }

        /// <summary>
        /// 登录个人中心
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public async void TVCLogin(string username, string password, bool md5 = true)
        {
            try
            {
                TVCenter center = new TVCenter();

                TVCUserLoginModel loginModel = new TVCUserLoginModel();
                loginModel.username = username;
                if (md5)
                    loginModel.password = password.ToMD5();
                else
                    loginModel.password = password;
                loginModel.platform = 2;

                var result = await center.UserLogin(loginModel);

                if (result.success)
                {
                    if (result.data == null || (result.data.zwNumber == null | result.data.zwPassword == null))
                    {
                        throw new Exception("ERR UserLogin result is null");
                    }
                    TVCenterResponse_Data data = result.data;
                    tempUsername = data.zwNumber;
                    tempPassword = data.zwPassword;
                    OcxApi.bLogonServer2(tempUsername, tempPassword, tempPassword);
                }
                else if (result.msg == "用户名或密码错误")
                {
                    LoginEvent?.Invoke(403, result.msg);
                }
                else
                {
                    LoginEvent?.Invoke(4, result.msg);
                }
            }
            catch (Exception ex)
            {
                TVLog.WriteLine(ex.Message);

                LoginEvent?.Invoke(4, ex.Message);
            }
        }


        private async Task<TVCenterResponse> TVCQuerycompanyinfo(TVCQuerycompanyinfoModel model)
        {
            TVCenter center = new TVCenter();

            var result = await center.Querycompanyinfo(model);

            return result;
        }

        private void Log(string log)
        {
            TVLog.WriteLine("LoginManger : " + log);
        }

        public void Dispose()
        {
            OcxApi.LogonResultEvent -= OcxApi_LogonResultEvent;
            OcxApi.RegisterSoftPhoneToSSEvent -= OcxApi_RegisterSoftPhoneToSSEvent;
        }
    }
}
